import pymysql
from typing import Tuple

class DatabaseInitializer:
    """
    数据库初始化类，用于创建必要的表结构
    """
    
    @staticmethod
    def init_database(host: str, port: int, user: str, password: str, database: str) -> Tuple[bool, str]:
        """
        初始化数据库，检查表是否存在，不存在则创建
        
        Args:
            host: 数据库主机
            port: 数据库端口
            user: 数据库用户
            password: 数据库密码
            database: 数据库名称
            
        Returns:
            (成功标志, 消息)
        """
        try:
            # 连接数据库
            conn = pymysql.connect(
                host=host,
                port=port,
                user=user,
                password=password,
                database=database,
                charset='utf8mb4'
            )
            
            with conn.cursor() as cursor:
                # 检查表是否存在
                cursor.execute("SHOW TABLES LIKE 'send'")
                table_exists = cursor.fetchone() is not None
                
                # 创建所有必要的表
                tables_created = False
                
                # 1. 创建短信发送记录表（如果不存在）
                if not table_exists:
                    create_send_table_sql = """
                    CREATE TABLE `send` (
                      `ID` INT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
                      `PHONE` VARCHAR(50) NULL COMMENT '手机号码',
                      `IP` VARCHAR(50) NULL COMMENT 'IP地址',
                      `DDATE` DATETIME NULL COMMENT '发送时间',
                      `ccode` VARCHAR(50) NULL COMMENT '验证码',
                      `taskId` VARCHAR(50) NULL COMMENT '短信平台任务ID'
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='短信发送记录表';
                    """
                    cursor.execute(create_send_table_sql)
                    
                    # 创建索引
                    send_indexes = [
                        "CREATE INDEX `idx_phone` ON `send` (`PHONE`)" ,
                        "CREATE INDEX `idx_ip` ON `send` (`IP`)" ,
                        "CREATE INDEX `idx_ddate` ON `send` (`DDATE`)" ,
                        "CREATE INDEX `idx_id` ON `send` (`ID`)"
                    ]
                    
                    for index_sql in send_indexes:
                        cursor.execute(index_sql)
                    
                    tables_created = True
                
                # 2. 创建地区表（如果不存在）
                cursor.execute("SHOW TABLES LIKE 'region'")
                if not cursor.fetchone():
                    create_region_table_sql = """
                    CREATE TABLE `region` (
                      `id` INT AUTO_INCREMENT PRIMARY KEY COMMENT '地区ID',
                      `nation` VARCHAR(50) NOT NULL COMMENT '国家名称',
                      `number` VARCHAR(20) NULL COMMENT '地区编号',
                      `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                      `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                      UNIQUE KEY `uk_nation` (`nation`)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='地区信息表';
                    """
                    cursor.execute(create_region_table_sql)
                    tables_created = True
                
                # 3. 创建经销商表（如果不存在）
                cursor.execute("SHOW TABLES LIKE 'distributor'")
                if not cursor.fetchone():
                    create_distributor_table_sql = """
                    CREATE TABLE `distributor` (
                      `id` INT AUTO_INCREMENT PRIMARY KEY COMMENT '经销商ID',
                      `sale` VARCHAR(50) NULL COMMENT '负责人',
                      `nation` VARCHAR(50) NOT NULL COMMENT '国家',
                      `distributorName` VARCHAR(100) NOT NULL COMMENT '经销商名称',
                      `lat` VARCHAR(50) NULL COMMENT '纬度',
                      `lng` VARCHAR(50) NULL COMMENT '经度',
                      `email` VARCHAR(100) NULL COMMENT '邮箱',
                      `phone` VARCHAR(50) NULL COMMENT '电话',
                      `whatsApp` VARCHAR(50) NULL COMMENT 'WhatsApp',
                      `url` VARCHAR(255) NULL COMMENT '网址',
                      `address` VARCHAR(255) NULL COMMENT '地址',
                      `ico` VARCHAR(255) NULL COMMENT '图标URL',
                      `distance` VARCHAR(20) NULL COMMENT '距离',
                      `banner` VARCHAR(255) NULL COMMENT '横幅URL',
                      `state` INT DEFAULT 100 COMMENT '状态',
                      `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                      `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                      UNIQUE KEY `uk_nation_name` (`nation`, `distributorName`)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='经销商信息表';
                    """
                    cursor.execute(create_distributor_table_sql)
                    
                    # 创建索引
                    distributor_indexes = [
                        "CREATE INDEX `idx_nation` ON `distributor` (`nation`)" ,
                        "CREATE INDEX `idx_name` ON `distributor` (`distributorName`)" ,
                        "CREATE INDEX `idx_address` ON `distributor` (`address`)"
                    ]
                    
                    for index_sql in distributor_indexes:
                        cursor.execute(index_sql)
                    
                    tables_created = True
                
                if tables_created:
                    conn.commit()
                    return True, "所有表结构创建成功"
                else:
                    return True, "表已存在"
            
        except Exception as e:
            return False, f"数据库初始化失败: {str(e)}"
        finally:
            if 'conn' in locals():
                conn.close()